<template>
  <PageWrapDrawer :show="show" :isUpdate="true" 
  @success="onSubmit"
  @on-drawer-close="onClose">
    <Form name="basic"
          :model="insideData.data"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 16 }"
          autocomplete="off"
          layout="horizontal"
    >
      <Row>
        <Col span="12">
          <FormItem label="账号/工号" name="username" v-bind="validateInfos['data.username']">
            <a-input v-model:value="insideData.data.username"/>
          </FormItem>
        </Col>
        <Col span="12">
          <FormItem v-if="!isUpdate" label="密码" name="password" v-bind="validateInfos['data.password']">
            <a-input-password v-model:value="insideData.data.password"/>
          </FormItem>
        </Col>
        <Col span="12">
          <FormItem label="姓名" name="name" v-bind="validateInfos['data.name']">
            <a-input v-model:value="insideData.data.name"/>
          </FormItem>
        </Col>
        <Col span="12">
          <FormItem label="电话" name="phone" v-bind="validateInfos['data.phone']">
            <a-input v-model:value="insideData.data.phone"/>
          </FormItem>
        </Col>
        <Col span="12">
          <FormItem label="电子邮件" name="email" v-bind="validateInfos['data.email']">
            <a-input v-model:value="insideData.data.email"/>
          </FormItem>
        </Col>
        <Col span="12">
          <FormItem label="年龄" name="age">
            <InputNumber v-model:value="insideData.data.age" :min="0" :max="150"/>
          </FormItem>
        </Col>
        <Col span="12">
          <FormItem label="性别" name="gander">
            <RadioGroup v-model:value="insideData.data.gender">
              <Radio :value="1">男</Radio>
              <Radio :value="2">女</Radio>
              <Radio :value="0">未知</Radio>
            </RadioGroup>
          </FormItem>
        </Col>
        <Col span="12">
          <FormItem label="可用" name="enable">
            <RadioGroup v-model:value="insideData.data.enable" :disabled="insideData.data.id === 1">
              <Radio :value="1">启用</Radio>
              <Radio :value="0">禁用</Radio>
            </RadioGroup>
          </FormItem>
        </Col>
        <Col span="12">
          <FormItem label="所属组织" name="orgId">
            <Select v-model:value="insideData.data.orgId" allowClear placeholder="请选择"
            :disabled="insideData.data.id === 1"
            :options="selectedOptionsOrgList"/>
          </FormItem>
        </Col>
        <Col span="12">
          <FormItem label="所属角色" name="roles">
            <Select v-model:value="selectedRoleList" mode="tags" placeholder="请选择"
            :disabled="insideData.data.id === 1"
            :options="selectedOptionsRoleList"/>
          </FormItem>
        </Col>
        <Col span="24">
          <FormItem label="备注" name="memo">
            <a-textarea v-model:value="insideData.data.memo" placeholder="说点什么..."/>
          </FormItem>
        </Col>
      </Row>
    </Form>
  </PageWrapDrawer>
</template>
<script lang="ts" name="userDrawer" setup>
import {reactive, ref, toRaw, watchPostEffect} from 'vue';
import {PageWrapDrawer} from '/@/components/PageWrapDrawer'
import {create, update} from '/@/api/sys/user';
import {getListData as getRoleListData} from '/@/api/admin/role';
import {getListData as getOrgListData} from '/@/api/admin/org';
import {
  Form, FormItem,
  InputNumber,
  Row, Col,
  Radio, RadioGroup,
  Select,
} from 'ant-design-vue';
import __ from 'lodash-es';

// https://blog.csdn.net/qq_49327308/article/details/124467691
// const {createMessage,} = useMessage();
// const {info, success, warning, error} = createMessage;

const emit = defineEmits(['on-success', 'on-drawer-close'])
const props = defineProps({
    show: Boolean,
    isUpdate: Boolean,
    row: {type: [Object, null] as PropType<Object | null>, default: null,},
})

const useForm = Form.useForm;
const insideData = reactive({
  data: {
    id: null,
    username: '',
    password: '',
    name: '',
    phone: '',
    email: '',
    age: 0,
    gender: 0,
    enable: 1,
    memo: '',
    roles: [],
    orgId: null,
  }
});
const selectedRoleList = ref([]);
const selectedOptionsRoleList = ref<any>([]);

const selectedOptionsOrgList = ref<any>([]);

const rulesRef = reactive({
  'data.username': [
    {required: true, message: '请输入账号/工号',},
  ],
  'data.password': [
    {required: true, message: '请输入密码',},
  ] as unknown,
  'data.name': [
    {required: true, message: '请输入姓名',},
  ],
  'data.phone': [
    {required: true, message: '请输入电话',},
  ],
});
watchPostEffect(async () => {
  let v1 = props.row as any
  if (v1) {
    insideData.data = {...v1}
    selectedRoleList.value = v1.roles.map((e:any) => e.id)
    if (!v1.orgId) insideData.data.orgId = null
  }

  if (props.show && v1?.id !== 1) {
    await getRoleListData().then(d => {
      selectedOptionsRoleList.value = d.map(e => {
        return {label: e.name, value: e.id}
      })
    })
    await getOrgListData().then(d => {
      selectedOptionsOrgList.value = d.map(e => {
        return {label: `${e.code}-${e.name}`, value: e.id, disabled: !(e.enable > 0),}
      })
    })
  }
  if (props.show && props.isUpdate) {
    delete rulesRef['data.password']
  }
})

const {resetFields, validate, validateInfos} = useForm(insideData, rulesRef, {
  onValidate: (...args) => {
  },
});

const onSubmit = () => {
  validate()
    .then(async () => {
      let data = toRaw(insideData.data)
      data.roles = selectedRoleList.value
      if (props.isUpdate) {
        await update(data).then(() => {
          onClose()
        })
      } else {
        await create(data).then(() => {
          onClose()
        })
      }
      emit('on-success')
    }).catch(err => {
    console.log('error-----', err);
  });
}

const onClose = () => {
  rulesRef['data.password'] = [
    {required: true, message: '请输入密码',},
  ]
  selectedRoleList.value = []
  selectedOptionsRoleList.value = []
  selectedOptionsOrgList.value = []
  Object.assign(insideData, {data: {}});
  resetFields();
  emit('on-drawer-close');
};

</script>
